﻿/*
 * @author: wizardc
 */

using DouEditor.Const;
using DouEditor.Utils;
using UnityEditor;
using UnityEngine;

namespace DouEditor.Asset
{
    /// <summary>
    /// 贴图文件处理
    /// 和项目强相关的处理类，指定文件夹下的贴图会被设置为一致的参数
    /// </summary>
    public class TextureMonitor : AssetPostprocessor
    {
        public static void SetTexturePlatformSettings(TextureImporter textureImporter, TextureImporterFormat textureImporterFormat, TextureWrapMode wrapMode, bool useMipMap, bool alphaIsTransparency)
        {
            textureImporter.mipmapEnabled = useMipMap;
            textureImporter.streamingMipmaps = useMipMap;
            
            textureImporter.wrapMode = wrapMode;
            textureImporter.isReadable = false;
            textureImporter.npotScale = TextureImporterNPOTScale.None;
            textureImporter.alphaIsTransparency = alphaIsTransparency;
            
            var android = textureImporter.GetPlatformTextureSettings("Android");
            if (!android.overridden)
            {
                android.overridden = true;
                android.format = textureImporterFormat;
                android.maxTextureSize = textureImporter.maxTextureSize;
                textureImporter.SetPlatformTextureSettings(android);
            }
            
            var ios = textureImporter.GetPlatformTextureSettings("iPhone");
            if (!ios.overridden)
            {
                ios.overridden = true;
                ios.format = android.format;
                ios.maxTextureSize = android.maxTextureSize;
                ios.resizeAlgorithm = android.resizeAlgorithm;
                ios.compressionQuality = android.compressionQuality;
                textureImporter.SetPlatformTextureSettings(ios);
            }
            
            EditorUtility.SetDirty(textureImporter);
            textureImporter.SaveAndReimport();
        }
        
        private const string UITexture = BuildConst.ABResFolder + "/Textures/";
        
        void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
        {
            for (int i = 0; i < movedAssets.Length; i++)
            {
                var path = movedAssets[i];
                ApplyTextureSetting(path);
            }
        }

        void OnPreprocessTexture()
        {
            ApplyTextureSetting(assetPath);
        }

        void OnPostprocessTexture()
        {
        }

        private void ApplyTextureSetting(string assetPath)
        {
            assetPath = EditorUtil.FormatPath(assetPath);
            var textureImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter;
            if (textureImporter == null)
            {
                return;
            }
            if (assetPath.StartsWith(UITexture))
            {
                SetTexturePlatformSettings(textureImporter, TextureImporterFormat.ASTC_4x4, TextureWrapMode.Clamp, false, true);
            }
        }
    }
}
